<?php
declare(strict_types=1);

namespace App\Logic\User\Service\Emo;

use App\Library\HttpClient;
use App\Logic\User\Repository\Emo\EmoImageRepository;
use App\Logic\User\Service\UserServiceInterface;
use Closure;
use Illuminate\Support\Facades\Storage;

class EmoImageService implements UserServiceInterface
{

    public static function searchWhere(array $requestParams): Closure
    {
        return function ($query) use ($requestParams) {
            extract($requestParams);
            $query->where("is_show", "=", 1);
            $query->where("group_uid", "=", $group_uid);
        };
    }

    public function serviceSelect(array $requestParams): array
    {
        return (new EmoImageRepository())->repositorySelect(self::searchWhere($requestParams),
            (int)($requestParams["size"] ?? 8), ["uid", "path", "url"]);
    }

    public function serviceCreate(array $requestParams): array
    {
        return [];
    }

    public function serviceUpdate(array $requestParams): array
    {
        return [];
    }

    public function serviceDelete(array $requestParams): int
    {
        return 0;
    }

    public function serviceFind(array $requestParams): array
    {
        $image = (new EmoImageRepository())->repositoryFind(function ($query) use ($requestParams) {
            $query->where("uid", "=", $requestParams["uid"]);
        }, ["url", "path"]);
        $downloadFile = Storage::disk("public_disk")->put($image["path"], (new HttpClient())::client()->get($image["url"] . $image["path"], ['verify' => false])->getBody());
        if ($downloadFile) {
            return [
                "url"  => config("app.url") . $image["path"],
                "msg"  => "地址获取成功",
                "code" => 1,
            ];
        }
        return [
            "url"  => "",
            "msg"  => "地址获取失败",
            "code" => 0,
        ];
    }
}
